package com.globant.twittersearch;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

public class ExternalStorage {

	public void saveImage(Bitmap bm, String imageName) {

		if(isPossibleWrite()) {
			String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
			String directoryPath = extStorageDirectory + "/twitterSearch";
			
			File file = new File(directoryPath);
			if(!file.exists()) {
				file.mkdirs();
			}
			
			OutputStream outStream = null;
			file = new File(directoryPath, "/" + imageName + ".png");
			try {
				outStream = new FileOutputStream(file);
				bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
				outStream.flush();
				outStream.close();
				
				Log.i("Hub", "OK, Image Saved to SD");
				Log.i("Hub", "height = " + bm.getHeight() + ", width = " + bm.getWidth());
				
			} catch (FileNotFoundException e) {
				Log.i("Hub", "FileNotFoundException: " + e.toString());
				
			} catch (IOException e) {
				Log.i("Hub", "IOException: " + e.toString());
			}
		} else {
			Log.i("Hub", "The memory card is not mounted");
		}
		

	}
	
	public Boolean existImage(String imageName) {
		if(!isSDMounted()) {
			return Boolean.FALSE;
		}
		
		String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
		String directoryPath = extStorageDirectory + "/twitterSearch/";
		File file = new File(directoryPath, "/" + imageName + ".png");
		
		return file.exists();
	}
	
	public Bitmap obtainImage(String imageName) {
		if(!isSDMounted()) {
			return null;
		}
		
		String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
		String directoryPath = extStorageDirectory + "/twitterSearch/" + imageName + ".png";
		
		return BitmapFactory.decodeFile(directoryPath);
	}
	
	
	private Boolean isSDMounted() {
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			mExternalStorageWriteable = true;
		} 
		
		return mExternalStorageWriteable;
	}
	
	
	private Boolean isPossibleWrite() {
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
		    mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
		    mExternalStorageWriteable = false;
		} else {
			mExternalStorageWriteable = false;
		}
		
		return mExternalStorageWriteable;
	}
}
